# core/config/platform_parsers/weibo_parser.py
import asyncio
import re
import json
import aiohttp
from typing import Dict, Any, Optional
from urllib.parse import unquote

PLATFORM_NAME = "微博"


class WeiboClient:
    """微博平台专属客户端（封装所有抓取逻辑）"""

    def __init__(self, cookie_str: str):
        self.cookies = self._parse_cookies(cookie_str)
        self.headers = self._build_headers()
        self.session: Optional[aiohttp.ClientSession] = None

    async def __aenter__(self):
        self.session = aiohttp.ClientSession(
            headers=self.headers,
            cookies=self.cookies,
            connector=aiohttp.TCPConnector(ssl=False),
            auto_decompress=True
        )
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.session:
            await self.session.close()

    @staticmethod
    def _parse_cookies(cookie_str: str) -> Dict[str, str]:
        """将Cookie字符串解析为字典"""
        cookies = {}
        for pair in cookie_str.replace('; ', ';').split(';'):
            if '=' in pair:
                key, value = pair.split('=', 1)
                cookies[key.strip()] = unquote(value.strip())
        return cookies

    @staticmethod
    def _build_headers() -> Dict[str, str]:
        """生成微博专用请求头"""
        return {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
            'Accept': 'application/json, text/plain, */*',
            'X-Requested-With': 'XMLHttpRequest',
            'Referer': 'https://weibo.com/'
        }

    @staticmethod
    def extract_weibo_id(url: str) -> str:
        """从URL提取微博ID"""
        patterns = [
            r'weibo\.com/\d+/(\w+)',
            r'weibo\.com/\w+/(\w+)',
            r'm\.weibo\.cn/detail/(\d+)',
            r'm\.weibo\.cn/status/(\w+)'
        ]
        for pattern in patterns:
            match = re.search(pattern, url)
            if match:
                return match.group(1)
        raise ValueError(f"Invalid Weibo URL: {url}")

    @staticmethod
    def validate_cookie(cookie_str: str) -> bool:
        """
        验证微博 Cookie 有效性
        :param cookie_str: 从配置文件中读取的原始 Cookie 字符串
        :return: 是否有效
        """
        if not cookie_str:
            print("[CRITICAL] 微博 Cookie 为空")
            return False

        required_keys = {"SUB", "XSRF-TOKEN", "WBPSESS"}
        present_keys = set()

        # 解析 Cookie 键值对
        for pair in cookie_str.split(';'):
            pair = pair.strip()
            if '=' in pair:
                key = pair.split('=')[0]
                present_keys.add(key)

        missing = required_keys - present_keys
        if missing:
            print(f"[CRITICAL] 微博 Cookie 缺少关键字段: {missing}")
            return False

        print("[DEBUG] 微博 Cookie 有效性验证通过")
        return True

    async def fetch_data(self, url: str) -> Dict[str, Any]:
        """主抓取入口（对齐001.py流程）"""
        if not self.session:
            raise RuntimeError("Session not initialized")

        weibo_id = self.extract_weibo_id(url)
        api_urls = [
            f"https://weibo.com/ajax/statuses/show?id={weibo_id}",
            f"https://weibo.com/ajax/statuses/longtext?id={weibo_id}"
        ]

        # 访问原始页面触发验证
        async with self.session.get(url, allow_redirects=False) as resp:
            if resp.status in (301, 302, 303, 307, 308):
                redirect_url = str(resp.headers.get('Location', ''))
                if "passport.weibo.com" in redirect_url:
                    raise PermissionError(f"Verification required: {redirect_url}")
                return await self.fetch_data(redirect_url)
            await resp.read()

        # 请求API端点
        for api_url in api_urls:
            try:
                async with self.session.get(api_url) as resp:
                    if resp.status != 200:
                        continue

                    data = await resp.json()
                    if data.get('ok') == 1:
                        return self._format_result(data)
            except (aiohttp.ClientError, json.JSONDecodeError):
                continue

        raise ValueError("All API requests failed")

    @staticmethod
    def _format_result(data: Dict) -> Dict[str, Any]:
        """统一格式化结果"""
        return {
            'status': 'success',
            'message': 'Weibo API parsed',
            'likes': data.get('attitudes_count', 0),
            'comments': data.get('comments_count', 0),
            'shares': data.get('reposts_count', 0)
        }


def parse_weibo(html: str, url: str, cookie_str: str) -> Dict[str, Any]:
    """平台解析器统一入口"""

    async def _async_parse():
        async with WeiboClient(cookie_str) as client:
            try:
                return await client.fetch_data(url)
            except Exception as e:
                return {
                    'status': 'error',
                    'message': str(e),
                    'likes': 0,
                    'comments': 0,
                    'shares': 0
                }

    # 在事件循环中运行异步代码
    loop = asyncio.new_event_loop()
    try:
        return loop.run_until_complete(_async_parse())
    finally:
        loop.close()